package com.muchenxinxi.androidbaseapp.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * ┏--------------------
 * │        /) /)
 * │     ฅ(• ﻌ •)ฅ
 * │  Created by HaoKing on 2017/2/23.
 * │  www.muchenxinxi.com
 * │  www.nextdever.com
 * │  QQ:773693552
 * │  QQ群: Geek Chat 344386592
 * ┗--------------------
 */

public class ViewCopyUtils {

    private ViewCopyUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static View copyView(Context context, View sourceView) {
        try {
            Class<? extends View> sourceClass = sourceView.getClass();

            Constructor<? extends View> constructor = sourceClass
                    .getConstructor(Context.class);
            View copyView = constructor.newInstance(context);

            copyField(sourceClass, sourceView, copyView);

            return copyView;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copyField(Class<?> sourceClass, View sourceView, View copyView) {
        Field[] declaredFields = sourceClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            try {
                Field field = declaredFields[i];
                if ("mParent".equals(field.getName()) && "android.view.View".equals(sourceClass.getName())) {
                    continue;
                }
                field.setAccessible(true);
                Object sourceObj = field.get(sourceView);

                if (sourceObj instanceof Drawable) {
                    sourceObj = ((Drawable) sourceObj).mutate();
                }

                field.set(copyView, sourceObj);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Class<?> superclass = sourceClass.getSuperclass();
        if (!"android.view.View".equals(sourceClass.getName())
                && superclass != null) {
            copyField(superclass, sourceView, copyView);
        }
    }
}
